package pre.promise.howie.interfaces;

public abstract class IHandler<T>{
    protected abstract void onError(Exception e, ICapture icapture);
    protected abstract void onExecute(INotify<T> notify, IPromise<T> ipromise);

    private INotify<T> notify;
    private IPromise<T> ipromise;

    private ICapture icapture;
    private IHandler pre_handler;
    private boolean isclose = false;

    public IHandler getPreHandler() {
        return pre_handler;
    }

    public void setPreHandler(IHandler handler) {
        pre_handler = handler;
    }

    public void toClose() {
        isclose = true;
    }

    public void load(IPromise<T> ipromise, INotify<T> notify) {
        this.notify = notify;
        this.ipromise = ipromise;
    }

    public boolean execute() {
        if(isclose){
            return false;
        }
    	if(this.ipromise != null){
    		this.onExecute(this.notify, this.ipromise);
        }
        return true;
    }

    public void error(Exception e) {
        this.pre_handler.toClose();
        if(this.icapture != null){
            this.onError(e, this.icapture);
        }else if(notify != null){
            notify.reject(e);
        }else{
        	System.out.println(e);
        }
    }

    public void setICapture(ICapture icapture) {
        this.icapture = icapture;
    }

}